'use strict';

let { Users } = require('../models');

module.exports = async (ctx, next) => {
    let userId = ctx.session.userId;
    let surveyId = ctx.session.surveyId;

    if (!userId) {
        if (ctx.path === '/' ) {
            await next();
        }else if(ctx.path === '/login'){
            await next();
        }else {
            // console.log("id:"+ctx.params.id); 
            ctx.session.surveyId = ctx.params.id;
            ctx.redirect('/login');
        }
    } else {
        let user = JSON.parse(JSON.stringify(await Users.findOne({
            where: {
                id: userId
            }
        })));

        if (user.role === '1') {
            if (ctx.path === '/login') {
                ctx.redirect('/surveyAll');
            } else if (ctx.path === '/rootindex') {
                ctx.redirect('/surveyAll');
            } else {
                await next();
            }
        } else if (user.role === '2') {
            if (ctx.path === '/login') {
                ctx.redirect('/rootindex');
            } else if (ctx.path === '/surveyAll') {
                ctx.redirect('/rootindex');
            } else {
                await next();
            }
        }
    }
}